package com.clkj.cldisabledmanclient.mvp.recovertrainapply;

import android.util.Log;

import com.clkj.cldisabledmanclient.bean.InstitutionBean;
import com.clkj.cldisabledmanclient.bean.PersonInfo;
import com.clkj.cldisabledmanclient.constant.Common;
import com.clkj.cldisabledmanclient.constant.Config;
import com.clkj.cldisabledmanclient.constant.TipStr;
import com.clkj.cldisabledmanclient.http.HttpService;
import com.clkj.cldisabledmanclient.util.DesUtil;
import com.clkj.cldisabledmanclient.util.scheduler.BaseSchedulerProvider;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by clboys on 2019/5/15.
 */

public class RecoverTrainApplyPresenter implements RecoverTrainApplyContract.Presenter {


    @NonNull
    RecoverTrainApplyContract.View mView;

    @NonNull
    private final BaseSchedulerProvider mSchedulerProvider;

    @NonNull
    private final HttpService mHttpService;

    @NonNull
    private CompositeDisposable mDisposables;


    public RecoverTrainApplyPresenter(@NonNull RecoverTrainApplyContract.View view, @NonNull BaseSchedulerProvider mSchedulerProvider
            , @NonNull HttpService httpService) {
        this.mView = view;
        this.mSchedulerProvider = mSchedulerProvider;

        this.mDisposables = new CompositeDisposable();
        this.mHttpService = httpService;

        this.mView.setPresenter(this);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mDisposables.dispose();
        mDisposables = null;
    }


    @Override
    public void getPersonInfo(String IdCard) {

        mView.showLoading();
        mHttpService.getMyPersonInfo(IdCard)
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.getPersonInfoError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }


                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {

                            Log.e("getPersonInfo信息", DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY));
                            String data = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);

                            PersonInfo personInfo = new Gson().fromJson(data, new TypeToken<PersonInfo>() {
                            }.getType());
                            mView.getPersonInfoSuccess(personInfo);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getPersonInfoError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);


                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();
                        mView.getPersonInfoError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getRegionXian() {

        mView.showLoading();
        mHttpService.getRegionalism()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.getRegionXianError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {
                            jsonStr = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                            Log.e("getRegionXian", jsonStr);
                            JsonObject object = new Gson().fromJson(jsonStr, new TypeToken<JsonObject>() {
                            }.getType());
                            String regions = object.get("regionalism").getAsString();

                            String[] regionss = regions.split(",");


                            mView.getRegionXianSuccess(regionss);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getRegionXianError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);


                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();

                        mView.getRegionXianError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getDisableType() {
        mView.showLoading();
        mHttpService.getDisabilityCategory()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.getDisableTypeError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {


                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {
                            jsonStr = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                            Log.e("getDisabilityCategory", jsonStr);
                            JsonObject object = new Gson().fromJson(jsonStr, new TypeToken<JsonObject>() {
                            }.getType());
                            String types = object.get("disabilityCategory").getAsString();

                            String[] typess = types.split(",");


                            mView.getDisableTypeSuccess(typess);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getDisableTypeError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);


                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();

                        mView.getDisableTypeError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getOrgnizeByDiableType(String disabilityCategory) {

        mView.showLoading();
        mHttpService.getInstitutionByDisabilityCategory(disabilityCategory)
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {

                            mView.getOrgnizeByDiableTypeError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {
                            jsonStr = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                            Log.e("getOrgnizeByDiableType", jsonStr);

                            List<InstitutionBean> institutionBeans = new Gson().fromJson(jsonStr, new TypeToken<List<InstitutionBean>>() {
                            }.getType());
                            mView.getOrgnizeByDiableTypeSuccess(institutionBeans);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getOrgnizeByDiableTypeError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);


                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();

                        mView.getOrgnizeByDiableTypeError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getFamilyTypes() {
        mView.showLoading();
        mHttpService.getFamilyCategory()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.getFamilyTypesError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {
                            jsonStr = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                            Log.e("getFamilyTypes", jsonStr);
                            JsonObject object = new Gson().fromJson(jsonStr, new TypeToken<JsonObject>() {
                            }.getType());
                            String types = object.get("familyCategory").getAsString();

                            String[] typess = types.split(",");


                            mView.getFamilyTypesSuccess(typess);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getFamilyTypesError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();
                        mView.getFamilyTypesError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getEconomicSource() {
        mView.showLoading();
        mHttpService.getEconomicSource()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.getEconomicSourceError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {


                        String jsonStr = jsonObject.get(Common.RESPONSE_KEY_DATA).getAsString();

                        try {
                            jsonStr = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                            Log.e("getDisabilityCategory", jsonStr);
                            JsonObject object = new Gson().fromJson(jsonStr, new TypeToken<JsonObject>() {
                            }.getType());
                            String types = object.get("economicSource").getAsString();

                            String[] typess = types.split(",");


                            mView.getEconomicSourceSuccess(typess);

                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.getEconomicSourceError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);


                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();
                        mView.getEconomicSourceError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void addApply(RequestBody area, RequestBody country, RequestBody name, RequestBody gender, RequestBody birthday, RequestBody disabilityCategory,
                         RequestBody IdCard, RequestBody address, RequestBody guardianName, RequestBody guardianRelationship, RequestBody guardianCompany,
                         RequestBody guardianTel, RequestBody guardianName2, RequestBody guardianRelationship2, RequestBody guardianCompany2,
                         RequestBody guardianTel2, RequestBody familyCategory, RequestBody economicSource, RequestBody personnelAnnualIncome,
                         RequestBody institutionId, RequestBody reasonDemand, MultipartBody.Part personnelImgageMap,
                         MultipartBody.Part guardianIDCardMap, MultipartBody.Part guardianResidenceBookletMap,
                         MultipartBody.Part childrenResidenceBookletMap, MultipartBody.Part lowAssuranceMap,
                         MultipartBody.Part disabilityCertificateMap, MultipartBody.Part hospitalProveMap) {

        mView.showLoading();

        mHttpService.submitApply(area, country, name, gender, birthday, disabilityCategory, IdCard, address, guardianName, guardianRelationship, guardianCompany, guardianTel,
                guardianName2, guardianRelationship2, guardianCompany2, guardianTel2, familyCategory, economicSource, personnelAnnualIncome, institutionId, reasonDemand,
                personnelImgageMap, guardianIDCardMap, guardianResidenceBookletMap, childrenResidenceBookletMap, lowAssuranceMap, disabilityCertificateMap, hospitalProveMap)
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        Log.e("submitApply", jsonObject.toString());
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.addApplyError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        mView.addApplySuccess("提交成功");

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();
                        mView.addApplyError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void addApply2(RequestBody area, RequestBody country, RequestBody name, RequestBody gender, RequestBody birthday, RequestBody disabilityCategory,
                          RequestBody IdCard, RequestBody address, RequestBody guardianName, RequestBody guardianRelationship, RequestBody guardianCompany,
                          RequestBody guardianTel, RequestBody guardianName2, RequestBody guardianRelationship2, RequestBody guardianCompany2,
                          RequestBody guardianTel2, RequestBody familyCategory, RequestBody economicSource, RequestBody personnelAnnualIncome,
                          RequestBody institutionId, RequestBody reasonDemand, MultipartBody.Part personnelImgageMap,
                          MultipartBody.Part guardianIDCardMap, MultipartBody.Part guardianResidenceBookletMap,
                          MultipartBody.Part childrenResidenceBookletMap, MultipartBody.Part lowAssuranceMap,
                          MultipartBody.Part hospitalProveMap) {

        mView.showLoading();

        mHttpService.submitApply2(area, country, name, gender, birthday, disabilityCategory, IdCard, address, guardianName, guardianRelationship, guardianCompany, guardianTel,
                guardianName2, guardianRelationship2, guardianCompany2, guardianTel2, familyCategory, economicSource, personnelAnnualIncome, institutionId, reasonDemand,
                personnelImgageMap, guardianIDCardMap, guardianResidenceBookletMap, childrenResidenceBookletMap, lowAssuranceMap, hospitalProveMap)
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<JsonObject>() {
                    @Override
                    public boolean test(@NonNull JsonObject jsonObject) throws Exception {
                        mView.dismissLoading();
                        Log.e("submitApply", jsonObject.toString());
                        if (!jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            mView.addApplyError(jsonObject.get(Common.RESPONSE_KEY_MSG).getAsString());
                        }

                        return jsonObject.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS);

                    }
                })
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposables.add(d);
                    }

                    @Override
                    public void onNext(@NonNull JsonObject jsonObject) {

                        mView.addApplySuccess("提交成功");

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mView.dismissLoading();
                        e.printStackTrace();
                        mView.addApplyError(TipStr.TIP_SERVER_GET_DATA_WRONG_AND_TRY_LATER);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}
